package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.Teacher;
import com.example.temp.mapper.TeacherMapper;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherMapper teacherMapper;

    // 添加教师
    @PostMapping("/insert")
    public Result insertTeacher(@RequestBody Teacher teacher){
        int teacher1 = teacherMapper.insert(teacher);
        return Result.success(teacher1);
    }

    // 分页查询
    @GetMapping("/showPage")
    public Result showPageTeacher(@RequestParam String query, @RequestParam Integer pageNum, @RequestParam Integer pageSize){
        List<Teacher> teachers;
        int total;
        Map<String, Object> params = new HashMap<>();
        params.put("query",query);
        params.put("pageNum",(pageNum-1) * pageSize);
        params.put("pageSize",pageSize);
        teachers = teacherMapper.search(params);
        total = teacherMapper.getTotal(query);
        return Result.success(total,teachers);
    }

    // 查询教师信息
    @GetMapping("/query")
    public Result findTeacher(@RequestParam String teacherID) {
        try {
            // 如果需要，可以转换字符串ID为整型
            Teacher teacher = teacherMapper.findByID(teacherID);
            if (teacher == null) {
                return Result.fail("教师信息不存在");
            }
            return Result.success(teacher);
        } catch (Exception e) {
            return Result.fail("查询教师信息失败: " + e.getMessage());
        }
    }

    // 更新教师信息
    @PostMapping("/update")
    public Result updateTeacher(@RequestBody Teacher teacher) {
        int teacher1 = teacherMapper.update(teacher);
        return Result.success(teacher1);
    }

    @DeleteMapping("/{id}")
    public Result deleteTeacher(@PathVariable("id") String teacherID) {
        int teacher = teacherMapper.deleteByID(teacherID);
        return Result.success(teacher);
    }

    // 获取所有教师ID和姓名
    @GetMapping("/acquireInfo")
    public Result acquireInfo(){
        List<Map<String,String>> info = teacherMapper.acquireInfo();
        return Result.success(info);
    }
    
    // 获取所有教师信息
    @GetMapping("/findAll")
    public Result findAllTeachers() {
        try {
            List<Teacher> teachers = teacherMapper.findAll();
            return Result.success(teachers);
        } catch (Exception e) {
            return Result.fail("获取教师列表失败: " + e.getMessage());
        }
    }
}
